package com.platform.uaa.service;

import cn.hutool.core.collection.CollUtil;
import com.platform.uaa.constant.MessageConstant;
import com.platform.uaa.config.ClientsProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户端管理业务类
 *
 * @author zyk
 */
@Primary
@Component("customClientDetailsService")
public class CustomClientDetailsServiceImpl implements ClientDetailsService {

  private List<ClientsProperties.Client> clientList;
  private final PasswordEncoder passwordEncoder;
  private final ClientsProperties clientsProperties;

  public CustomClientDetailsServiceImpl(PasswordEncoder passwordEncoder, ClientsProperties clientsProperties) {
    this.passwordEncoder = passwordEncoder;
    this.clientsProperties = clientsProperties;
  }

  @PostConstruct
  public void initData() {
    // 1、密码模式
    clientList = clientsProperties.getClients();
  }

  @Override
  public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
    List<ClientsProperties.Client> findClientList = clientList.stream().filter(item -> item.getClientId().equals(clientId)).collect(Collectors.toList());
    if (CollUtil.isEmpty(findClientList)) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND, MessageConstant.NOT_FOUND_CLIENT);
    }
    return new CustomClientDetails(findClientList.get(0));
  }
}
